package tgc.edu.exam.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import org.omg.CORBA.OBJECT_NOT_EXIST;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.entity.SysDept;
import tgc.edu.exam.service.SysDeptService;
import tgc.edu.exam.web.form.SysDeptForm;

@Controller
@RequestMapping(value="/dept")
public class SysDeptController extends CommonController<SysDept, UUID, SysDeptForm>{
	@Autowired
	private SysDeptService service;

	@Override
	public void edit(SysDeptForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		SysDept model=new SysDept();
		UUID id = form.getId();
		UUID parentId = form.getParentId();
		if(id!=null) {
			model=service.findById(id);
		}
		if(parentId!=null) {
			model.setParent(service.findById(parentId));
		}
		map.put("model", model);
	}
	
	@RequestMapping("/combotree")
	@ResponseBody
	public Object combotree(SysDeptForm form) {
		UUID id = form.getId();
		List<SysDept> list=service.findByParentIsNullOrderByIdx1();
		return buildTree(list,id);
		
		
	}

	private Object buildTree(List<SysDept> list, UUID id) {
		List<HashMap<String, Object>> result=new ArrayList<>();
		for (SysDept dept : list) {
			if(dept.getId()!=id) {
				HashMap<String, Object> node=new HashMap<>();
				node.put("id", dept.getId());
				node.put("text",dept.getName());
				node.put("pid", dept.getParentId());
				node.put("nodes",buildTree(dept.getChildren(), id));
				result.add(node);
			}
		}
		return result;
	}

	@Override
	public Object save(SysDeptForm form) {
		SysDept model=new SysDept();
		UUID parentId = form.getParentId();
		UUID id = form.getId();
		if(id!=null) {
			model=service.findById(id);
		}
		if(parentId!=null) {
			model.setParent(service.findById(parentId));
		}
		model.setName(form.getName());
		model.setIdx1(form.getIdx1());
		service.save(model);
		return new AjaxResult("数据保存成功");
	}

}
